<template>
  <div class='container'>
  <el-dialog
     :title="form.id ? '修改目录':'新增目录' "
     width="30%"
     :visible="showDialog"
     @close='close'>
     <!-- 表单 -->
     <el-form ref="form" :model="form"  label-width="80px" :rules="rules"  size="mini">
     <el-form-item v-if="!subjects" label="所属学科" prop="subjectID">
     <el-select placeholder="请选择" style="width:100%"
      v-model="form.subjectID"
      >
      <el-option
      v-for="item in subject"
      :key="item.value"
      :label="item.label"
      :value="item.value" ></el-option>
    </el-select>
  </el-form-item>
   <el-form-item label="目录名称" prop="tagName">
    <el-input v-model="form.tagName"></el-input>
  </el-form-item>
     </el-form>
     <span slot="footer" class="dialog-footer">
    <el-button @click="close">取 消</el-button>
    <el-button type="primary" @click="add">确 定</el-button>
  </span>
</el-dialog>
  </div>
</template>

<script>
import { add, update } from '@/api/hmmm/tags.js'
import { simple } from '@/api/hmmm/subjects.js'
export default {
  name: 'TagsAdd',
  props: {
    showDialog: {
      type: Boolean,
      default: false
    },
    subjects: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      form: {
        id: '',
        subjectID: '',
        tagName: ''
      },
      rules: {
        tagName: [
          { required: true, message: '不能为空' }

        ],
        subjectID: [
          { required: true, message: '内容不能为空' }

        ]
      },
      value: 'value',
      subject: []
    }
  },
  async created () {
    const { data } = await simple()
    this.subject = data
  },
  watch: {
    subjects: {
      deep: true,
      handler (vel) {
        if (!this.subjects) {
          this.form.subjectID = ''
        } else {
          this.form.subjectID = +this.subjects
        }
      },
      immediate: true
    }
  },
  methods: {
    close () {
      this.$emit('update:showDialog', false)
      this.form = {
        id: '',
        subjectID: '',
        tagName: ''
      }
      this.$refs.form.resetFields()
    },
    async add () {
      // console.log(this.form)
      try {
        await this.$refs.form.validate()
      } catch {
        return
      }
      if (this.form.id) {
        await update(this.form)
        this.$emit('getList')
        this.$message.success('修改成功')
        this.$emit('update:showDialog', false)
      } else {
        // 发送请求，添加员工
        await add({ ...this.form })
        this.$message.success('添加成功')
        // 添加成功关闭框
        this.$emit('update:showDialog', false)
        // 发送给父组件重新渲染
        this.$emit('getList')
        // 清空
        this.form = {
          id: '',
          tagName: '',
          subjectID: ''
        }
        // 清空校验
        this.$refs.form.resetFields()
      }
    }

  }
}
</script>

<style scoped lang='less'></style>
